package com.example.userservice.controller;

import com.example.userservice.client.CourseClient;
import com.example.userservice.client.EnrollClient;
import com.example.userservice.client.LearnFlagClient;
import com.example.userservice.entity.user_account;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping
public class StudentController {

    @Autowired
    private CourseClient courseClient;
    
    @Autowired
    private EnrollClient enrollClient;
    
    @Autowired
    private LearnFlagClient learnFlagClient;

    // 学生主页
    @GetMapping("/student/home")
    public String studentHome(HttpSession session, Model model) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        model.addAttribute("user", user);
        return "HomeStu";
    }

    // 课程详情页面
    @GetMapping("/student/course/{courseId}")
    public String courseDetail(@PathVariable int courseId, HttpSession session, Model model) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "redirect:/login";
        }
        
        // 获取课程信息
        List<Map<String, Object>> allCourses = courseClient.listAllCourses();
        Map<String, Object> courseInfo = allCourses.stream()
                .filter(course -> (Integer) course.get("id") == courseId)
                .findFirst()
                .orElse(null);
        
        if (courseInfo == null) {
            return "redirect:/student/home";
        }
        
        // 获取课程章节
        List<Map<String, Object>> chapters = courseClient.listChapters(courseId);
        
        // 获取每个章节的课件
        Map<Integer, List<Map<String, Object>>> chapterMaterials = new HashMap<>();
        for (Map<String, Object> chapter : chapters) {
            int chapterId = (Integer) chapter.get("id");
            List<Map<String, Object>> materials = courseClient.getChapterMaterials(courseId, chapterId);
            chapterMaterials.put(chapterId, materials);
        }
        
        model.addAttribute("user", user);
        model.addAttribute("course", courseInfo);
        model.addAttribute("chapters", chapters);
        model.addAttribute("chapterMaterials", chapterMaterials);
        
        return "course";
    }

    // 获取所有可选课程
    @GetMapping("/student/courses/all")
    @ResponseBody
    public List<Map<String, Object>> getAllCourses() {
        return courseClient.listAllCourses();
    }

    // 获取学生已选课程
    @GetMapping("/student/courses/my")
    @ResponseBody
    public List<Map<String, Object>> getMyCourses(HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return List.of();
        }
        return enrollClient.getStudentEnrollments((int) user.getId());
    }
    
    // ==================== 章节完成相关API ====================
    
    // 标记章节为已完成
    @PostMapping("/student/chapter/complete")
    @ResponseBody
    public String completeChapter(@RequestParam int courseId, @RequestParam int chapterId, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("userId", user.getId());
            requestBody.put("courseId", courseId);
            requestBody.put("chapterId", chapterId);
            
            return learnFlagClient.completeChapter(requestBody);
        } catch (Exception e) {
            e.printStackTrace();
            return "标记完成失败: " + e.getMessage();
        }
    }
    
    // 获取课程的章节完成情况
    @GetMapping("/student/course/{courseId}/completions")
    @ResponseBody
    public Object getCourseCompletions(@PathVariable int courseId, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            return learnFlagClient.getUserChapterCompletions(user.getId(), courseId);
        } catch (Exception e) {
            e.printStackTrace();
            return "获取完成情况失败: " + e.getMessage();
        }
    }
    
    // 检查章节是否已完成
    @GetMapping("/student/chapter/{chapterId}/completion")
    @ResponseBody
    public Object checkChapterCompletion(@PathVariable int chapterId, HttpSession session) {
        user_account user = (user_account) session.getAttribute("user");
        if (user == null) {
            return "未登录";
        }
        
        try {
            return learnFlagClient.checkChapterCompletion(user.getId(), chapterId);
        } catch (Exception e) {
            e.printStackTrace();
            return "检查完成状态失败: " + e.getMessage();
        }
    }
}